<template>
  <div class="page">
    <h1>购物车</h1>
    <hr />
    <div>
      <h3>添加课程</h3>
      <section>
        <div>
          课程名称：
          <input type="text" v-model="inputCourse.name" />
        </div>
        <div>
          课程价格：
          <input type="text" v-model="inputCourse.price" />
        </div>
        <div>
          <button @click="addCourse">添加课程到列表</button>
        </div>
      </section>
    </div>
    <hr />
    <table>
      <tr>
        <th>课程名称</th>
        <th colspan="2">课程价格</th>
      </tr>
      <tr v-for="(item,index) in courseData" :key="item.id">
        <td>{{item.name}}</td>
        <td>{{item.price}}</td>
        <td>
          <button @click="addToCart(index)">添加到购物车</button>
        </td>
      </tr>
    </table>
    <hr />
    <Cart :cartData="cartData" @removeItem="removeItem" />
  </div>
</template>

<script type="text/ecmascript-6">
import Cart from "@/components/Cart";
export default {
  //beforeRouteEnter拿不到this，因为当时vue还未构建
  beforeRouteEnter(to, from, next) {
    console.log("组件before router enter");
    next();
  },
  //改变参数时
  beforeRouteUpdate(to, from, next) {
    console.log("组件before router upldate");
    next();
  },
  beforeRouteLeave(to, from, next) {
    console.log("组件before router leave");
    next();
  },
  props: ["id"],
  data() {
    return {
      inputCourse: {
        name: "",
        price: ""
      },
      courseData: [
        {
          name: "web全栈开发构架师",
          price: 111
        }
      ],
      cartData: []
    };
  },
  components: { Cart },
  methods: {
    addCourse() {
      this.courseData.push({ ...this.inputCourse });
    },
    addToCart(index) {
      let item = { ...this.courseData[index] };
      let isHasCourt = this.cartData.find(o => o.name === item.name);
      if (isHasCourt) {
        isHasCourt.number += 1;
      } else {
        item.number = 1;
        item.isActive = true;
        //this.cartData.push(item);
        //新对象会出发刷新，增加getset，老对象至增加一个属性，不会出发
        //console.log(item);
        this.cartData.push(item);

        // this.cartData.push({
        //   ...item,
        //   number: 1,
        //   isActive: true
        // });
      }
    },
    removeItem(index) {
      this.cartData.splice(index, 1);
    }
  },
  mounted() {
    console.log(this.id);
  }
};
</script>

<style scoped>
</style>
